<template>
  <div class="login">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model.number="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >登录路</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { API } from "../../api/index";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { log } from "console";
const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  username: "",
  password: "",
});
//
const checkPass = (_: any, value: string, callback: any) => {
  if (value === "") {
    return callback(new Error("请输入密码"));
  }
  return callback();
};

const checkUser = (_: any, value: string, callback: any) => {
  if (value === "") {
    return callback(new Error("请输入用户名"));
  }
  return callback();
};

//
const rules = reactive<FormRules<typeof ruleForm>>({
  password: [
    { validator: checkPass, trigger: "blur" },
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  username: [
    { validator: checkUser, trigger: "blur" },
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
      API["login"](ruleForm).then((res: any) => {
        if (res.data.code === 200) {
          // 将数据存储到本地存储了里面
          localStorage.setItem("user", JSON.stringify(res.data.data));
          console.log(res.data.data, "user!");
          let path = (route.query.redirect as string) || "/";
          setTimeout(() => {
            router.push(path);
          }, 2000);
        } else {
          console.log("错误的");
        }
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #2b4b6b;
  .demo-ruleForm {
    padding: 20px 5vw;
    background: #fff;
    border-radius: 5px;
  }
}
</style>
